package com.nf.health.app.datamain.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.adapter.OxygenBooladShowAdapter;
import com.nf.health.app.models.BloodoOygenBean;
import com.nf.health.app.utils.DateUtil;
import com.nf.health.app.utils.Util;
import com.nf.health.app.utils.ViewUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 血痒的测量结果
 */
public class BloodOxygenResultyActivity extends BaseActivity {
    public static  final String REFRESH_BROADCAST_MEASUREE_OXYGEN = "com.nf.health.app.activity.BloodOxygenResulty";
    public static  final String UPLoad_BROADCAST_MEASUREE_OXYGEN = "com.nf.health.app.activity.BloodOxygenResulty";
    @Bind(R.id.tv_heartRate)
    TextView tv_heartRate;
    @Bind(R.id.tv_blood_oxygen)
    TextView tv_blood_oxygen;
    @Bind(R.id.tv_oxygen_time)
    TextView tv_oxygen_time;
    @Bind(R.id.iv_oxygen_result_bk_temprerture)
    ImageView iv_oxygen_result_bk_temprerture;
    @Bind(R.id.btn_blood_oxygen_measure)
    Button btn_blood_oxygen_measure;
    @Bind(R.id.lv_measure_oxygem)
    ListView lv_measure_oxygem;
    @Bind(R.id.ll_line)
    View ll_line;//显示的一个线
    private OxygenBooladShowAdapter adapter;
    private BroadcastReceiver myBroadcastReceiver;
    private ArrayList<BloodoOygenBean> list;
    private int images[] = {
            R.drawable.oxygen_finish_left_bg,
            R.drawable.oxygen_finish_right_bg,
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_blood_oxygen_measured_result);
        ButterKnife.bind(this);
        ViewUtil.setText(this, R.id.titlebar_title_tv, "测量结果");
        iv_oxygen_result_bk_temprerture.setAdjustViewBounds(true);
        btn_blood_oxygen_measure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //显示测量结果
        initData();
        levelJudgmentByFat(0);
        registerReceiver();
    }

    /**
     *
     * @return 健康等级
     */
    private int levelJudgmentByFat(double bloodOxygen) {
        int type = 0;
        if (bloodOxygen > 0 & bloodOxygen < 90) {
            type = 0 ;
        }else if(bloodOxygen <= 0){
            type = 1;
        }
        iv_oxygen_result_bk_temprerture.setImageResource(images[type]); //不会变形
        return type;
    }
    /**
     * 初使化广播的方法
     */
    private void registerReceiver() {
        myBroadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (null == action) {
                    return;
                }
                if (REFRESH_BROADCAST_MEASUREE_OXYGEN.equals(action)) {
                    BloodoOygenBean model = (BloodoOygenBean) intent.getSerializableExtra(REFRESH_BROADCAST_MEASUREE_OXYGEN);
                    refreshListViewAdapter(model);
                    //Constants.SAVELIST.add(model);//添加到大集合中
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(REFRESH_BROADCAST_MEASUREE_OXYGEN);
        this.registerReceiver(myBroadcastReceiver, intentFilter);
    }

    /**
     *
     *初始化数据
     *
     */
    private void initData() {
        btn_blood_oxygen_measure.setOnClickListener(this);
        list = new ArrayList<BloodoOygenBean>();
        BloodoOygenBean model = new BloodoOygenBean();
        ll_line.setVisibility(View.GONE);
        if(adapter == null){
            adapter = new OxygenBooladShowAdapter(this,list);
            lv_measure_oxygem.setAdapter(adapter);

        }else{
            adapter.updateAdapterData(list);
        }
        tv_heartRate.setText("0");
        tv_blood_oxygen.setText(String.valueOf(0));
        levelJudgmentByFat(1);
        //给测量设置时间
        tv_oxygen_time.setText(DateUtil.date2String(System.currentTimeMillis(),"yyyy-MM-dd"));
    }
    /**
     * 接受数目,刷新动画
     */
    private void refreshData(double temperature) {

    }
    /**
     * 当点击一级菜单时的处理操作
     *
     */
    private void refreshListViewAdapter(BloodoOygenBean model) {
        if(model == null){
            return ;
        }
        if(list.size() == 0){
            list.add(model);
        }else if(list.size() > 0){
            list.set(0,model);
        }
        levelJudgmentByFat(model.getOxygenValue());
        ll_line.setVisibility(View.GONE);
        tv_heartRate.setText(String.valueOf(model.getHeartRate()));//给脉率值设置
        tv_blood_oxygen.setText(String.valueOf(model.getOxygenValue()));//给血痒值设置
        if(adapter == null){
            adapter = new OxygenBooladShowAdapter(this,list);
            lv_measure_oxygem.setAdapter(adapter);
        }else{
            adapter.updateAdapterData(list);
        }
        // 为List设置动画效果()
        Util.setListAnimation(lv_measure_oxygem);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.btn_blood_oxygen_measure:
                if(list.size() <= 0){//数目上传
                    showToast("暂无数据可上传");
                    return;
                }
                //ptype	设备类型	string	1 手动输入 2恩福产品
                //sweat	数据	string	SON [{"sp2":"汗液", "rate":"体温", "time":"时间"},{"sp2":"汗液", "rate":"体温", "time":"时间"}]
                try {
                    JSONArray  jsonArray = new JSONArray();
                    for(int i = 0 ; i < list.size();i++){
                        BloodoOygenBean model = list.get(i);
                        JSONObject obj = new JSONObject();
                        obj.put("sp2", String.valueOf(model.getOxygenValue()));
                        obj.put("rate",String.valueOf(model.getHeartRate()));
                        obj.put("time",String.valueOf(model.getCurrentTime()));
                        jsonArray.put(i,obj);
                    }
                    if(jsonArray.length() > 0){
                        provider.upLoadBloodOxygen("2",jsonArray.toString(),UPLoad_BROADCAST_MEASUREE_OXYGEN);
                    }
                }catch (JSONException e) {
                    e.printStackTrace();
                   // showToast("s");
                }
                break;
        }
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        if(UPLoad_BROADCAST_MEASUREE_OXYGEN.equals(actionName)){
            Intent intent = new Intent(BloodOxygenActivity.ACTION_OXYGENTION_HISTORY);
            intent.putExtra("getOxygenDate", list.get(0));
            sendBroadcast(intent);
            finish();
        }
    }
}
